package controller

import (
	"fmt"
	"gin/TEST01/dao"
	"gin/TEST01/entity"
	"gin/common"
	"gin/common/constant"
	"gin/common/util"
	sysEntity "gin/system/entity"
	sysService "gin/system/service"
	sysUtil "gin/system/util"
	"github.com/gin-gonic/gin"
	"log"
)

type User struct {
	UserId   int
	UserName string
	NickName string
	Password string
}

type PageHelper struct {
	pageNum  int
	pageSize int
}

//add
func SaveUser(c *gin.Context) {
	loginBody := &sysEntity.LoginBody{}
	c.BindJSON(&loginBody)

	//TODO 默认密码123456
	//密码加密
	userName := loginBody.UserName
	password := loginBody.Password
	log.Println("接收到的用户名称为："+userName)
	log.Println("接收到的用户密码为："+password)
	//不为空校验传参
	if userName == "" {
		common.ReturnError(c, constant.ERRORCODE(), util.MapToJson("用户名不能为空"), nil, int64(len("0")))
		panic("")
	}

	if password == "" {
		common.ReturnError(c, constant.ERRORCODE(), util.MapToJson("密码不能为空"), nil, int64(len("0")))
		panic("")
	}

	//加密
	plainText := []byte(password)
	cipherText, err := sysUtil.RsaEncrypt(plainText, "./public.pem")
	if err != nil {
		fmt.Println(err)
		log.Println("==================加密发生异常")
	}
	fmt.Printf("加密后为:%s\n", cipherText)

	//db-password 加密赋值
	loginBody.Password = string(cipherText)
	//执行保存
	user := sysService.AddUser(c, loginBody)
	log.Println(user)
}

//getByUserId
func GetUserById(context *gin.Context) {
	user := &User{}
	context.BindJSON(&user)
	viewUser := dao.GetUserById(user.UserId)
	common.ReturnSucess(context, constant.SUCCESSCODE(), constant.SUCCESSDBMSG, viewUser, 1)
}

/***
1.查询返回数据集合
2.uer中传参，并接收
*/
func GetByUserList(c *gin.Context) {
	//申明新对象
	//user := &User{}

	//前台的传参的body中的json转对象
	//c.BindJSON(&user)

	//给user对象的userName赋值
	//TODO user.UserName = c.Query("UserName")

	//与Query 的作用相同
	//TODO getQuery, _ := c.GetQuery("UserName")
	//TODO fmt.Println("1.使用getQuery 方法获取的 UserName的值为：" + getQuery)

	//获取接口地址url上传的参数值，(eg: http://127.0.0.1:9999/getByUserList/?UserName=admin, 获取 “admin" 的 )
	//TODO query := c.Query("UserName")
	//TODO fmt.Println("2.接口url中传的 UserName，使用Query方法获取的值为：" + query)

	//获取分页参数
	pageNum := c.Query("pageNum")
	pageSize := c.Query("pageSize")
	fmt.Println("分页参数分别为 ：" + pageNum + "|" + pageSize)

	/*list := dao.GetUserByList(user)
	i := len(list)
	fmt.Print(i)
	common.ReturnSucess(c, 200, "查询成功", list, int64(len(list)))*/
}

/***
1.多表 联合 orm
*/
func GetByUserJoinList(c *gin.Context) {
	//申明新对象
	user := &entity.SysUserEntity{}

	//获取分页参数
	pageNum := c.Query("pageNum")
	pageSize := c.Query("pageSize")
	fmt.Println("分页参数分别为 ：" + pageNum + "|" + pageSize)

	list := dao.GetByUserJoinList(c, (*entity.SysUserEntity)(user))
	i := len(list)
	fmt.Print(i)
	common.ReturnSucess(c, constant.SUCCESSCODE(), constant.SUCCESSDBMSG, list, int64(len(list)))
}
